<?php
namespace app\queen\controller;
use app\common\model\Redis;
use app\common\model\Dev_info;
use app\common\model\Dev_api;
use app\common\model\Devs_share;
use app\common\model\Dev_data_info;
use app\common\model\Program;
use app\common\model\Alarm_info;
use think\Controller;
use think\Session;
class UserDevs extends Controller {
    public $redis;
    
    public function __construct(){
        
        parent::__construct();

        $this->redis = new Redis();
    }


    /**
     * 验证SESSION 中设备是否存在
     */
    public function checkDevs($dev_id=false){
        
        if($dev_id){
            $uid = session('user.id')
            $devs = session('user.devs');
            if(!in_array($dev_id,$devs)){
                //若不是本人操作,则查看是否是 共享人设备
                $shareModel = new Devs_share();
                $info =  $shareModel->selAuth($uid,$dev_id);
                if($info){
                    if($info["valid"]){   
                        //判断是否有时间限制 0:无限制
                        if($info["et"]!=0){
                            if($info["st"]>time() || $info["et"]<time()){
                                exit;
                            }
                        }
                    }else{
                        //无效
                        exit;
                    }
                }else{
                    //不存在
                    exit;
                }
            }
        }
    }

    /**
     * 获取用户设备信息
     * @return [json] 设备id值、设备名称、设备状态、最后更新时间
     */
    public function getAllMyDevs(){

    	if(request()->isAjax()){
	        $uid = session('user.id');
	        $devModel = new Dev_info();

	        $devlist = $devModel->getAll(['owner'=>$uid],'id,name,state,guid1');
	        //从redis 中获取最后更新时间
	        if($devlist){
	            $dev = array();
	            foreach($devlist as $key => $value){
	                
	                $select = $this->redis->whereRedis($value["guid1"]);
	                if(is_bool($select)){
	                    $devlist[$key]["update_t"] = "";
	                }else{
	                    $this->redis->select($select);
	                    $devlist[$key]["update_t"] = $this->redis->hget($value["guid1"],"last_upload");
	                }
	                
	                //将该用户的所有设备guid1值存入session
	                $dev[$key] = $value["guid1"]; 
	            }
	            session::set('user.devs',$dev);
	        }
	        $data["user"] = session('user.name');
	        $data["devs"] = $devlist;
	        exit(json_encode($data));
    	}
    }

    /**
     * 获取用户所有设备参数信息
     */
    public function getDevsDataInfo(){

    	if(request()->isAjax()){
	        $this->checkDevs();
        
	        $devModel = new Dev_data_info();

	        $dev_id = input("post.devs_id");
	        $ops = input("post.ops");
	        if($dev_id){
	            $devinfo = $dev_id;
	        }else{
	            //如果不存在查所有设备值
	            $devinfo = session('user.devs');
	        }
	        if($ops){
	            //外部小程序
	            $ops = json_decode($ops,true);
	            if($ops){
	                $ProgramHelper = new Program();
	                foreach ($ops as $key => $value) {
	                   //检查类文件中是否存在一个方法
	                   $istrue = method_exists($ProgramHelper,$value["name"]);
	                   if($istrue){
	                        //argv 为参数
	                        $argv = isset($value["args"])?$value["args"]:"";
	                        $ProgramHelper->{$value["name"]}($argv);
	                   }
	                }
	            }
	        }

	        $data = array();
	        foreach ($devinfo as $_k => $_v) {

	            $field = "d_id,name,thr_val1,thr_val2,when_alarm";
	            $info = $devModel->getAll(["guid1"=>$_v],$field);
	            $data[$_k]["dev_id"] = $_v;
	            foreach ($info as $key => $value) {
	                
	                //能从redis中获取的从redis中获取,不能的就从mysql中获取
	                $data[$_k]["d_ids"][$key] = $value["d_id"];
	                $data[$_k]["names"][$key] = $value["name"];
	                $data[$_k]["if_his"][$key] = $devModel->if_his($_v,$value["d_id"]);
	                $data[$_k]["units"][$key] = $devModel->units($_v,$value["d_id"]);
	                $data[$_k]["alarm_condi"][$key] = $value["when_alarm"];
	                $data[$_k]["thr_val1"][$key] = $value["thr_val1"];
	                $data[$_k]["thr_val2"][$key] = $value["thr_val2"];
	            }
	        }
	        exit(json_encode($data));
    	}


    }

    /**
     * 获取设备当天数据
     * @param [string] $dev_id [设备guid]
     * @param [string] $t [web当前拥有的最新数据时间戳(秒为单位).0表示web端目前没有任何该设备数据]
     * @return [json]
     */
    public function getTheDevData(){

    	if(request()->isAjax()){
	        $guid1 = input("post.dev_id","","string");
	        $t = input("post.t","","string");
	        
	        $view = 1;

	        if($t>0 && $t-time()>30){
	            exit;
	        }
	        //获取设备当天数据
	        $devHelp = new Dev_info();
	        $data = $devHelp->getDayData($guid1,$view,$t);
	        
		    //压缩输出
	        phpGzip(json_encode($data));
    	}
    }

    /**
     * 获取设备历史数据
     * @param [string] $dev_id [设备号]
     * @param [string] $d_id [操作id]
     * @param [string] $st [开始时间,时间戳]
     * @param [string] $et [结束时间,时间戳]
     * @return [type] [description]
     */
    public function getTheDevHisData(){
        
        if(request()->isAjax()){
	        $guid1 = input("post.dev_id","","string");
	        $d_id = input("post.d_id","","string");
	        $st = input("post.st","","string");
	        $et = input("post.et","","string");

	        $uid = session('user.id');
	        
	        $view = 1;

	        //若$st大于$et,则退出
	        if($st>$et){
	            exit;
	        }

	        $table = get_his_data_table($guid1);

	        $this->redis->select(1);
	        $unit = $this->redis->hget($guid1."_para_info",$d_id);
	        $data = array();
	        
	        //当天凌晨整点时间戳
	        $stDat = strtotime(date('Y-m-d',time()));
	        
	        //开始时间从00:00:00开始
	        $st = strtotime(date("Y-m-d",$st));
	        //结束时间 到23:59:59
	        $et = strtotime(date("Y-m-d",$et+3600*24))-1;
	        
	        if($et>$stDat){
	            //如果结束时间大于 当天凌晨时间,则将当天数据导入mysql
	            $devModel = new Dev_info();
	            $devModel->dayDataMysql($guid1);
	        }

	        $where["guid1"] = $guid1;
	        $where["d_id"] = $d_id;
	        $where['view'] = $view;
	        $where['t']  = array('between',array($st,$et));

	        $res = M($table)->where($where)->field("bin_str,val,t")->select();
	        if($res){
	            $res = $res->getData();
	        }
	        switch ($unit) {
	            case 'sys/bin':
	            case 'sys/state-bin':
	                if($res){
	                     $i=0;
	                     foreach ($res as $_v) {
	                         $data["v"][$i] = $_v["bin_str"];
	                         $data["t"][$i] = $_v["t"];
	                         $i++;
	                     }
	                }
	                exit(json_encode($data));
	                break;
	            case 'sys/file':
	            case 'sys/file-image':
	                if($res){
	                     $i=0;
	                     foreach ($res as $_v) {
	                         $file = "upload_file/".$uid."/".$_v["bin_str"];
	                         $data["v"][$i] = $file;
	                         $data["t"][$i] = $_v["t"];
	                         $i++;
	                     }
	                }
	                exit(json_encode($data));
	                break;
	            case 'sys/file-pcloud':
	                if($res){
	                     $i=0;
	                     foreach ($res as $_v) {
	                         $file = "uploads/".$uid."/".$_v["bin_str"];
	                         if(file_exists($file)){
	                             //读取二进制文件时，需要将第二个参数设置成'rb'
	                             $handle = fopen($file, "r");
	                             //通过filesize获得文件大小，将整个文件一下子读到一个字符串中
	                             $contents = fread($handle, filesize ($file));
	                             fclose($handle);
	                             $data["v"][$i] = $contents;
	                         }else{
	                             $data["v"][$i] = "";
	                         }
	                         $data["t"][$i] = $_v["t"];
	                         $i++;
	                     }
	                }
	                //压缩
	                phpGzip(json_encode($data));
	                break;
	            default:
	                if($res){
	                    $i=0;
	                    foreach($res as $_v){
	                       $data["v"][$i] = $_v["val"];
	                       $data["t"][$i] = $_v["t"];
	                       $i++;
	                    }
	                }
	                exit(json_encode($data));
	                break;
	        }
        }
    }

    /**
     * 获取设备历史数据某日最后一条数据
     * @param [string] $dev_id [设备号]
     * @param [array] $d_id [操作id]
     * @param [string] $st [开始时间]
     * @param [string] $et [结束时间]
     * @return [type] [description]
     */
    public function getLastHisData(){

    	if(request()->isAjax()){
	        $guid1 = input("post.dev_id","","string");
	        $d_id = input("post.d_id");
	        $st = input("post.st","","string");
	        $view = 1;

	        $table = get_his_data_table($guid1);
	        $t = strtotime($st)+86400;
	        $data = array();
	        $where["guid1"] = $guid1;
	        $where['view'] = $view;
	        $where['t']  = array('lt',$t);

	        $data = array();
	        foreach ($d_id as $key => $value) {
	            $where["d_id"] = $value;
	            $res = M($table)->where($where)->field("bin_str,val,t")->order("t desc")->limit(1)->find();

	            if($res){
	            	$res = $res->getData();
	            }
	            $data[$value]["val"] = $res["val"];
	            $data[$value]["t"] = $res["t"];
	            unset($res);
	        }
	        exit(json_encode($data));
    	}
    }

    /**
     * 获取设备操作接口信息
     * @param [array] devs_id [设备号]
     */
    public function getDevsApis(){

        if(request()->isAjax()){
        	$this->checkDevs();
	        $devapiModel = new Dev_api();
	        $devInfoModel = new Dev_info();


	        $dev_id = I("post.devs_id");
	        if($dev_id){
	            $devinfo = $dev_id;
	        }else{
	            //如果不存在查所有设备值
	            $devinfo = $_SESSION["devs"];
	        }
	        $data = array();
	        foreach($devinfo as $_k=>$_v){

	            $devInfo = $devapiModel->getAll(['guid1'=>$_v],"*");
	            $devInfo = endoceArr($devInfo);
	            
	            if($devInfo){
	                $model = $devInfoModel->getOne(['guid1'=>$_v],'model');
	                
	                $data[$_k]["model"] = $model["model"];

	                $data[$_k]["dev_id"] = $_v;
	                foreach ($devInfo as $key => $value) {
	        
	                    $remark = $value["remark"]?$value["remark"]:"";
	                    $args = $value["args"]?$value["args"]:"";
	            
	                    $data[$_k]["apis_id"][$key] = $value["api_id"];
	                    $data[$_k]["apis_name"][$key] = $value["name"];
	                    $data[$_k]["apis_remark"][$key] = $remark;
	                    $data[$_k]["apis_hide"][$key] = $value["hide"];
	            
	                    if($args){
	                        
	                        $data[$_k]["apis_args"][$key] = $args;
	                    }else{
	                        $data[$_k]["apis_args"][$key] = null;
	                    }
	                }
	            }
	        }
	        exit(json_encode($data));
        }
    }

    /**
     * web端设备控制接口
     * @param [string] dev_id [设备号]
     * @param [string] api_id [控制的 api_id]
     * @param [array] argv [NULL 或 数组] 
     * @return [string] [OK:成功  否则失败]
     */
    public function devCtrl(){

        if(request()->isAjax()){
        	$uid = session('user.id');

	        $devid = input("post.dev_id");
	        $api_id = input("post.api_id");
	        $argv = input("post.argv");

	        $argv = $argv?$argv:array();

	        $devs = session('user.devs');

            if($devid){
	            //可控可视  有效无效
	            if(!in_array($devid, $devs)){

	                //若不是本人操作,则查看是否是 共享人设备
	                $shareModel = new Devs_share();
	                $info =  $shareModel->selAuth($uid,$devid);
	                if($info){
	                    if($info["auth"]!="FULL_SHARE" || $info["valid"]!=1){
	                        //若不是 可控,不是 有效,则停止
	                        exit;
	                    }
	                }else{
	                    exit;
	                }
	            }
	        }else{
	            exit;
	        }

            //查出设备在redis中几号数据库
	        $select = $this->redis->whereRedis($devid);

            if(is_bool($select)){
	            exit("NON");
	        }

     	   	//切换数据库
    		$this->redis->select($select);

	        //获取设备ip、port
       		$devip = $this->redis->hget($devid,"dev_ip");
        	$devport = $this->redis->hget($devid,"dev_port");

    	    //若不存在redis中则退出
	        if(!$devip || !$devport){
	            exit("NOQ");
	        }

	        //查看合法性,不合法都退出
	        //if(!checkIp($devip)){
	        //    exit("NOW");
	        //}
	        
	        if($devport>65535){
	            exit("NOE");
	        }

        	//获取服务器端ip、port,并socket操作
         	$server_ip = $this->redis->hget($devid,"server_ip");
         	$server_port = $this->redis->hget($devid,"server_port");

         	$data = json_encode(array("dev_id"=>$devid,"api_id"=>$api_id,"argv"=>$argv));

         	//判断控制类型是否属于tcp
 	        if(false !== strpos($devip, 'tcp')){
	            $res = $this->tcpCtrl($devip, $devport, $data);
	            exit($res);
	        }

            //set_time_limit(6);
	        $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
	        socket_set_option( $socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0 ) ); 
	        socket_set_option( $socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>3, "usec"=>0 ) ); 
	    
	        socket_set_option( $socket, SOL_SOCKET, SO_REUSEADDR, 1 );

	        $res = socket_bind($socket,$server_ip,$server_port);
            // if($res===false){
		    //         $text=socket_strerror(socket_last_error($socket));
		    //         socket_close($socket);
		    //         exit($text);
		    // }
		    
            socket_sendto($socket, $data,strlen($data), 0, $devip ,$devport);
	        socket_recvfrom($socket,$res,1024,0,$r_ip,$r_port);
	        socket_close($socket);

	        exit($res);
        }
    }

    /**
     * @param string $devip
     * @param string $devport
     * @param string $ins 控制指令
     * @return void
     * */
    public function tcpCtrl($devip, $devport, $data){
        //set_time_limit(6);
        $devip = explode('_', $devip);
        $devip = $devip[1];
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_set_option( $socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0 ) );
        socket_set_option( $socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>3, "usec"=>0 ) );
        
        socket_set_option( $socket, SOL_SOCKET, SO_REUSEADDR, 1 );
       
        $flag = socket_connect($socket, $devip, $devport);
        $len = strlen($data."\r\n");
        $str = "CTRL / HTTP/1.1\r\nContent-Length:$len\r\n\r\n".$data."\r\n";
        $send = socket_write($socket, $str, strlen($str));
        \Think\Log::write("send:$str,len:$send");
        $res = socket_read($socket, 1024);
        echo $res;
        socket_close($socket);
    }
    
    /**
     * PC端 UDP 控制
     * @return [type] [description]
     */
    public function pcUdp(){

		if(request()->isAjax()){
	        $devid = input("post.dev_id");
	        $api_id = input("post.api_id");
	        $argv = input("post.argv");

            $server_ip= "127.0.0.1";
	        $server_port = 80;

	        $data = json_encode(array("dev_id"=>$devid,"api_id"=>$api_id,"argv"=>$argv));

	        //set_time_limit(6);

	        $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
	        socket_set_option( $socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0 ) ); 
	        socket_set_option( $socket, SOL_SOCKET, SO_SNDTIMEO, array("sec"=>3, "usec"=>0 ) ); 
	    
	        socket_set_option( $socket, SOL_SOCKET, SO_REUSEADDR, 1 );

	        $ret = socket_sendto($socket, $data,strlen($data), 0, $server_ip ,$server_port);
	        if($ret===false){
	            $text=socket_strerror(socket_last_error($socket));
	            socket_close($socket);
	            exit($text);
	        } 
	        socket_close($socket);
		}
    }


    /**
     * 设备共享给谁
     * @param [string] dev_id [设备号]
     * @return [type] [description]
     */
    public function queryShare(){
        if(request()->isAjax()){

	        $uid = session('user.id');
	        $uid = session('user.devs');

	        $dev_id = input("post.dev_id");
	        
	        $this->checkDevs($dev_id);
	        
	        $shareModel = new Devs_share();

	        $data = $shareModel->selDevs($dev_id,false,$uid);

	        exit(json_encode($data));
        }
    }
    
    /**
     * 设备信息详情
     * @param [string] dev_id [设备号]
     * @return [type] [description]
     */
    public function dev_Info(){
       if(request()->isAjax()){
	       $dev_id = input("post.dev_id");
	       $devs = session('user.devs');
	    
	       if(!$dev_id){
	           exit;
	       }
	       $this->checkDevs($dev_id);

	       $devModel = new Dev_info();
	       $field = 'model,name,maker,nickname,state,longitude,latitude,tz';
	       $info = $devModel->getOne(['guid1'=>$dev_id],$field);
	       if($info){
	            //查出设备在redis中几号数据库
	            $select = $this->redis->whereRedis($dev_id);
	            if(is_bool($select)){
	                $info["upload_t"] = 0;
	                $info["tz"] = 8;
	            }else{
	                $this->redis->select($select);
	                $info["upload_t"] = $this->redis->hget($dev_id,"last_upload");
	                $info["tz"] = $this->redis->hget($dev_id,"tz");
	            }

	           exit(json_encode($info));
	       }else{
	           exit;
	       }
       }
    }
    
    /**
     * 添加设备共享
     * @param [string] dev_id [设备号]
     * @param [string] user [用户id/@用户名]
     * @param [string] auth [可控/可视]
     */
    public function addShare(){

        if(request()->isAjax()){
	        $devid = input('post.dev_id', false);
	        $share = input('post.user', false);
	        $auth = input('post.auth', 'SHARE_DATA');
	        $st = input('post.st','');
	        $et = input('post.et','');
	        $ispro = input('post.ispro','0');

	        $uid = session('user.id');
	        $devs = session('user.devs');
	        if(!($auth && $share && $devid)){
	           exit;
	        }
	        
	        if(!in_array($devid,$devs)){
	            exit;
	        }

            //时间验证
	        if($ispro){
	            $st = strtotime($st);
	            $et = strtotime($et);
	            if($st=="" || $et==""){
	                exit(json_encode(array("state"=>false,"msg"=>"请选择时间")));
	            }elseif($st>$et){
	                exit(json_encode(array("state"=>false,"msg"=>"时间选择有误")));
	            }
	        }else{
	            $st = time();
	            $et = 0;
	        }

            //校验共享人合法性
	        $shareModel = new Devs_share();
	        $res = $shareModel->checkSharerValid($devid, $share);

	        if(!$res['state']){
	        	exit(json_encode(['state'=>false,'msg'=>$res['msg']]));
	        }else{
	        	$shareid = $res['shareid'];
	        }

	        $ower_id = session('user.id');

            //共享记录表中加入共享记录
	        $id = $devsShare->add(array(
	            'guid1' => $devid,
	            'owner_id' => $ower_id,
	            'share_with' => $shareid['uid'],
	            'accept' => -1,
	            'addr' => $shareid['unionid'],
	            'st'=>$st,
	            'et'=>$et
	        ));

	        //发送共享邀请信息
	        // $content = "{$_SESSION['user']}用户向您共享 $devid 设备,您可能会收到来自该设备的信息,包括警报信息 .";
	        
	        //app推送共享信息
	        // $alarmModel = new \Common\Model\Alarm_tableModel();
	        // $alarmModel->sendAlarmToAPP( $shareid['uid'], $content);
	        
	        // $flag  = M('message_table')->add(array(
	        //             'sender' => $uid, 
	        //             'receiver' => $shareid['uid'],
	        //             'content' => $content,
	        //             'type' => 1,
	        //             'sendtime' => time(),
	        //             'remark' => $id
	        //          ));
	        
	        // if($flag) echo json_encode(array('state' => true, 'msg' => '已发送共享邀请，等待通过','id'=>$id));
	        // else echo json_encode(array('state' => false, 'msg' => '共享失败，请重试'));

	        exit(json_encode(['state'=>false,'msg'=>'已发送共享邀请，等待通过','id'=>$id]));
        }
    }
    
    /**
     *  检查共享人是否合法
     */
    public function checkSharerValid(){

    	if(request()->isAjax()){
    		$share = input('post.user', false) ? input('post.user') : exit();
	        $devid = input('post.dev_id', false) ? input('post.dev_id') : exit();

	        $devshareModel = new Devs_share();
	        $res = $devshareModel->checkSharerValid($devid, $share);

	        if($res['state']){
	        	exit(json_encode(array('state' => true, '合法')));
	        }else{
	        	exit(json_encode($res));
	        } 
    	}
    }
        
    /**
     * 解除共享
     */
    public function delShareDev(){

    	if(request()->isAjax()){
    		$id = input("post.ids");
	        $types = input("post.types",0);
	        $uid = $_SESSION["uid"];

	        $uid = session('user.id');

	        $flag = $types?true:false;
	        $shareModel = new Devs_share();
	        $return = $shareModel->cancelShare($id,$uid,$flag);

	        exit($return);
    	}
    }
    
    /**
     * 共享受益人接受共享邀请
     * @param [string] id 消息id
     * @return [array] 
     */
    public function replyInvite(){
        if(request()->isAjax()){
            $idMsg = input('post.id', false, 'intval');
            if(!$idMsg){
            	exit(json_encode(['state'=>$false]));
            }
            
            // $Obj = new \Common\Model\Message_table();
            // echo json_encode($Obj->agreeMsg($idMsg));
        }
    }
    
    /**
     * 共享受益人拒绝共享邀请
     * @param [string] id [消息id]
     */
    public function refuseInvite(){

       if(request()->isAjax()){
       		$idMsg = input('post.id', false);

       		if(!$idMsg){
            	exit(json_encode(['state'=>$false]));
            }

            // $Obj = new \Common\Model\Message_table();
       		// echo json_encode($Obj->refuseMsg($idMsg));
       }
    }    
    /**
     * 共享受益人解除设备共享 
     * @param [string] id [消息id]
     */
    public function beneficiaryStopDev(){
    	if(request()->isAjax()){
        	$uid = session('user.id');

        	$id = input('post.id', false);
        	if(!$id) exit();
        
        	$devs_share = new Devs_share();
        	$res = $devs_share->cancelShare($id);
        
        	$data['state'] = $res?true:false;

        	exit($data);
    	}
        
    }
    
    /**
     * 分享设备修改
     * @param [string] dev_id [设备id]
     * @param [string] share_with [共享给谁]
     * @param [string] auth [可控/可视  可为NULL]
     * @param [string] valid [有效/失效]
     */
    public function changeShareInfo(){
        if(request()->isAjax()){

	        $dev_id = input("post.dev_id");
	        //分享给某人
	        $share_with = input("post.share_with");
	        
	        $uid = session('user.id');
	        $devs = session('user.devs');
	        $auth = input("post.auth");
	        $valide = input("post.valid");

	        $this->checkDevs($dev_id);

	        if($auth=="" && $valide==""){
	            $data = array(
	                   "state"=>false,
	                   "msg"=>"参数有误"
	            );
	            exit(json_encode($data));
	        }

	        //先查给某人分享此用户是否存在(-1:所有人 >0:用户id号)
	        if($share_with>0){
	            $userModel = new User();
	            $shareid = $userModel->getOne('uid',['uid'=>$share_with]);
	            if(!$shareid){
	                $data = array(
	                       "state"=>false,
	                       "msg"=>"分享给此用户不存在"
	                );
	                exit(json_encode($data));
	            }
	        }

			if($auth){
	           $save["auth"] = $auth;
	        }else{
	           $save["valid"] = $valide;
	        }

           	$shareHelp = new Devs_share();

	        $where["guid1"] = $dev_id;
	        $where["owner_id"] = $uid;
	        $where["share_with"] = $share_with;

	        $res = $shareHelp->where($where)->save($save);
	        if($res){
	            if(isset(input("post.valid"))){
	                $Alarm_infoModle = new Alarm_info();
	                
	                if($valide) {
	                    //共享有效，在mysql、redis中添加通知地址
	                    $Alarm_infoModle->addAlarmAdr($dev_id, $share_with);
	                }else{
	                    //共享无效，在从mysql、redis中删除通知地址
	                    $Alarm_infoModle->delAddr($dev_id, $share_with);
	                }
	            }
	            $data = array(
	                   "state"=>true,
	            );
	        }else{
	            $data = array(
	                   "state"=>false,
	                   "msg"=>"修改失败"
	            );
	        }
	        exit(json_encode($data));
        }
    }
    
    /**
     * 查询、修改警报推送方式
     * @return [type] [description]
     */
    public function changeAlarmType(){
        $userModel = new User();
    
        $uid = session('user.id');

        if(request()->isGet()){
            //查询当前推送方式
            $data = [
        		'state'=>1,
        		'data'=>$userModel->getUserAlarmType($uid);
        	];
        	exit(json_encode($data));
        }else{
            //修改报警推送方式
            if(!isset($_POST['is_alert'])){
                exit;
            }

            if(!input('post.is_alert')){
            	exit;
            }

            $is_alert = input('post.is_alert');
            $type = input('post.type');

            //修改mysql警报推送方式
            $res = $userModel->changeMysqlAlarmType($uid, $is_alert, $type);
            if($res){
            	exit(json_encode(['state'=>0,'msg'=>'修改失败,请重试']));
            }
            
            $alarmModel = new Alarm_info();
            //重新生成将mysql警报地址并重新载到redis中
            $alarmModel->changeRedisAlarmType($uid);
            
            exit(json_encode(['state'=>1,'msg'=>'修改成功']));
        }
    }
    
    /**
     * 修改推送次数和间隔时间
     * @return [type] [description]
     */
    public function alarmAdvancedSeting(){
        $alarm_info = new Alarm_info();
        $uid = session('user.id');

        if(request()->isGet()){
            
            $dev_id = input('get.dev_id');
            //查出选中设备的警报间隔时间和次数
            if($dev_id){
            	$restle = $alarm_info->getAlarmSetting($dev_id,$uid);
            	exit(json_encode($restle));
            }

            $devModel = new Dev_info();
            $res = $devModel->getAll(['owner'=>$uid],'guid1',true);
            foreach ($res as $v){
            	$data[] = $v['guid1'];
            }
            exit(json_encode($data));
        }else{
            $num = input('post.num',false) ? input('post.num',false):exit;
            $intv = input('post.intv',false) ? input('post.intv',false):exit;
            $dev_id = input('post.dev_id',false) ? input('post.dev_id'):exit;
            
            $devModel = new Dev_info();
            if($dev_id == 'all'){
                foreach ($devModel->getUserDev($uid, 'guid1') as $v){
                    //修改mysql
                    $res = $alarm_info->devIntvTimeSeting($v['guid1'], $uid,['intv'=>$intv * 60, 'times_to_send' => $num]);
                    if(false == $res){
                        continue;
                    }
                    //修改redis
                    $alarm_info->ModifyAlarmSetting($v['guid1'], $num, $intv);
                }
                exit(json_encode(['state' => '1', 'msg' => '修改成功']));
            }else{
                $flag = $alarm_info->devIntvTimeSeting($dev_id,$uid,['intv'=>$intv,'times_to_send'=>$num]);

                if($flag) {
                    $alarm_info->ModifyAlarmSetting($dev_id, $num, $intv);
                    exit(json_encode(['state' => '1', 'msg' => '修改成功']));
                }else{
                	exit(json_encode(['state' => '1', 'msg' => '修改失败']));
                }
            }
        }
    }
}